package com.linhngua.code.gwt.server;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.xml.ws.handler.MessageContext;

import org.br.plotter.functions.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("/function")
public class FunctionEvalRS {
	
	private static final Logger		LOG				= LoggerFactory
															.getLogger(FunctionEvalRS.class);
	
	static final NumberFormat		NUMBER_FORMAT	= new DecimalFormat(
															"#.####");
	
	static Map<String, Function>	functionMap		= new HashMap<String, Function>();
	
	@Context
	MessageContext					messageContext;
	
	@Context
	HttpHeaders						headers;
	
	@Path("/eval")
	@Consumes(MediaType.WILDCARD)
	@POST
	/**
	 * x should be comma separated
	 */
	public String eval(@FormParam("functionText") String functionText,
			@FormParam("xArray") String xArray) {

		StringBuilder builder = new StringBuilder();
		try {
			// parse function
			Function f = functionMap.get(functionText);
			if (f == null) {
				
				f = Function.parseFunction(functionText);
				functionMap.put(functionText, f);
			}
			String xTokens[] = xArray.split(",");
			for (int i = 0; i < xTokens.length; i++) {
				String x = xTokens[i];
				double xv = Double.parseDouble(x);
				double y = f.eval(xv);
				builder.append(NUMBER_FORMAT.format(xv)).append(",")
						.append(NUMBER_FORMAT.format(y));
				if (i < xTokens.length - 1) {
					builder.append(",");
				}
			}
		}
		catch (Exception ex) {
			LOG.error("Error during function evaluation", ex);
		}
		
		return builder.toString();
		
	}
}
